<script setup lang="ts">
import { ref, reactive, h, onMounted } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { PaginationConfig, TableColumn } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import { ElMessage, ElMessageBox, ElTag, ElButton } from "element-plus";
import { Refresh } from "@element-plus/icons-vue";
import {
  getConfigList,
  updateConfig,
  testConfig,
  reloadConfig,
} from "../servers";

const props = defineProps<{
  task: string;
}>();

const loading = ref(false);
const configList = ref<any[]>([]);
const searchFormRef = ref<DynamicFormInstance>();

const searchForm = reactive({
  category: "",
});

const searchConfig: FormItemConfig[] = [
  {
    key: "category",
    name: "配置分类",
    type: "select",
    labelWidth: "80px",
    placeholder: "选择配置分类",
    params: {
      clearable: true,
      style: { width: "200px" },
      showPlaceholder: false,
      options: [
        { label: "全部", value: "" },
        { label: "备案API配置", value: "beian" },
        { label: "FOFA配置", value: "fofa" },
        { label: "系统配置", value: "system" },
      ],
    },
  },
];

const columns = ref<TableColumn[]>([
  {
    label: "配置键",
    prop: "config_key",
    width: 250,
    show: true,
  },
  {
    label: "配置值",
    prop: "config_value",
    minWidth: 300,
    show: true,
    render: (row) => {
      // 如果是敏感数据，显示脱敏

      const value = row.config_value || "";
      // 如果值长度小于等于10，用 ***
      if (value.length <= 10) {
        return "***";
      }
      // 长值：前4个字符 + **** + 后4个字符
      const front = value.substring(0, 4);
      const back = value.substring(value.length - 4);
      return `${front}****${back}`;
      return row.config_value;
    },
  },
  {
    label: "配置分类",
    prop: "config_category",
    width: 150,
    show: true,
    render: (row) => {
      const categoryMap = {
        beian: "备案API",
        fofa: "FOFA",
        system: "系统配置",
      };
      return categoryMap[row.config_category] || row.config_category;
    },
  },
  {
    label: "是否敏感",
    prop: "is_sensitive",
    width: 100,
    show: true,
    render: (row) => {
      return h(
        ElTag,
        { type: row.is_sensitive ? "danger" : "success", size: "small" },
        () => (row.is_sensitive ? "是" : "否")
      );
    },
  },
  {
    label: "操作",
    prop: "action",
    width: 180,
    show: true,
    slot: "action",
    fixed: "right",
  },
]);

const fetchConfigList = async () => {
  loading.value = true;
  try {
    const params: any = {
      hide_sensitive: true,
      ...searchForm,
    };
    // 移除空值
    Object.keys(params).forEach((key) => {
      if (
        params[key] === "" ||
        params[key] === null ||
        params[key] === undefined
      ) {
        delete params[key];
      }
    });
    const { data } = await getConfigList(params);
    configList.value = data.configs || [];
  } catch (error) {
    ElMessage.error("获取配置列表失败");
  } finally {
    loading.value = false;
  }
};

const handleSearch = (value: any) => {
  searchForm.category = value.category || "";
  fetchConfigList();
};

const handleSearchReset = () => {
  searchFormRef.value?.resetFields();
  searchForm.category = "";
  fetchConfigList();
};

const handleEdit = (row: any) => {
  // 如果是敏感数据且被隐藏了，传入空字符串让用户重新输入
  const currentValue = row.hide_sensitive ? "" : row.config_value;

  ElMessageBox.prompt("请输入新的配置值", `编辑配置: ${row.config_key}`, {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputValue: currentValue,
    inputType: row.is_sensitive ? "password" : "text",
  }).then(async ({ value }) => {
    try {
      await updateConfig({
        config_key: row.config_key,
        config_value: value,
      });
      ElMessage.success("配置更新成功");
      fetchConfigList();
    } catch (error) {
      ElMessage.error("配置更新失败");
    }
  });
};

const handleTestConnection = async (row: any) => {
  try {
    const configType = row.config_category === "beian" ? "beian" : "fofa";
    await testConfig({ config_type: configType });
    ElMessage.success("连接测试成功");
  } catch (error) {
    ElMessage.error("连接测试失败");
  }
};

const handleReloadConfig = async () => {
  ElMessageBox.confirm("确定要重载配置缓存吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await reloadConfig();
      ElMessage.success("配置缓存重载成功");
    } catch (error) {
      ElMessage.error("配置缓存重载失败");
    }
  });
};

onMounted(() => {
  fetchConfigList();
});
</script>

<template>
  <div>
    <el-card shadow="never">
      <div class="search-form-container">
        <DynamicForm
          ref="searchFormRef"
          v-model="searchForm"
          :form-config="searchConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleSearchReset"
        />
      </div>
    </el-card>

    <div style="height: 10px"></div>

    <el-card>
      <DynamicTable :columns="columns" :data="configList" :loading="loading">
        <template #toolbar-left>
          <el-button type="primary" :icon="Refresh" @click="fetchConfigList">
            刷新
          </el-button>
          <el-button type="warning" @click="handleReloadConfig">
            重载缓存
          </el-button>
        </template>

        <template #action="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button
            v-if="
              row.config_category === 'beian' || row.config_category === 'fofa'
            "
            type="success"
            size="small"
            @click="handleTestConnection(row)"
            >测试连接</el-button
          >
        </template>
      </DynamicTable>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.search-form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
</style>
